package com.ruoyi.vbze.service.impl;

import java.util.List;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.bean.BeanValidators;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.ruoyi.common.core.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.vbze.domain.Plant;
import com.ruoyi.vbze.mapper.BlockMapper;
import com.ruoyi.vbze.domain.Block;
import com.ruoyi.vbze.service.IBlockService;

/**
 * 地块管理Service业务层处理
 * 
 * @author vbze
 * @date 2023-02-22
 */
@Service
public class BlockServiceImpl implements IBlockService 
{
    private static final Logger log = LoggerFactory.getLogger(BlockServiceImpl.class);

    @Autowired
    private BlockMapper blockMapper;

    /**
     * 查询地块管理
     * 
     * @param id 地块管理主键
     * @return 地块管理
     */
    @Override
    public Block selectBlockById(Long id)
    {
        return blockMapper.selectBlockById(id);
    }

    /**
     * 查询地块管理列表
     * 
     * @param block 地块管理
     * @return 地块管理
     */
    @Override
    public List<Block> selectBlockList(Block block)
    {
        return blockMapper.selectBlockList(block);
    }

    /**
     * 新增地块管理
     * 
     * @param block 地块管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertBlock(Block block)
    {
        block.setCreateTime(DateUtils.getNowDate());
        block.setLastEditTime(DateUtils.getNowDate());
        int rows = blockMapper.insertBlock(block);
        insertPlant(block);
        return rows;
    }

    /**
     * 修改地块管理
     * 
     * @param block 地块管理
     * @return 结果
     */
    @Transactional
    @Override
    public int updateBlock(Block block)
    {
//        blockMapper.deletePlantByBlockNumber(block.getBlockNumber());
//        insertPlant(block);
        block.setLastEditTime(DateUtils.getNowDate());
        return blockMapper.updateBlock(block);
    }

    /**
     * 批量删除地块管理
     * 
     * @param ids 需要删除的地块管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteBlockByIds(Long[] ids)
    {
        blockMapper.deletePlantByBlockNumbers(ids);
        return blockMapper.deleteBlockByIds(ids);
    }

    /**
     * 删除地块管理信息
     * 
     * @param id 地块管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteBlockById(Long id)
    {
        blockMapper.deletePlantByBlockNumber(selectBlockById(id).getBlockNumber());
        return blockMapper.deleteBlockById(id);
    }

    /**
     * 新增植株管理信息
     * 
     * @param block 地块管理对象
     */
    public void insertPlant(Block block)
    {
        List<Plant> plantList = block.getPlantList();
//        Long id = block.getId();
        String blockNumber = block.getBlockNumber();
        if (StringUtils.isNotNull(plantList))
        {
            List<Plant> list = new ArrayList<Plant>();
            for (Plant plant : plantList)
            {
                plant.setBlockNumber(blockNumber);
                list.add(plant);
            }
            if (list.size() > 0)
            {
                blockMapper.batchPlant(list);
            }
        }
    }


    /**
     * 导入地块数据
     *
     * @param blockList 地块数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importBlock(List<Block> blockList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(blockList) || blockList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
//        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (Block block : blockList)
        {
            try
            {
                // 验证是否存在这个地块
//                SysUser u = userMapper.selectUserByUserName(block.getUserName());
                Block b = blockMapper.selectBlockByBlockNumber(block.getBlockNumber());
                if (StringUtils.isNull(b))
                {
//                    BeanValidators.validateWithException(validator, block);
//                    block.setPassword(SecurityUtils.encryptPassword(password));
                    block.setCreateBy(operName);
                    block.setUpdateBy(operName);
                    this.insertBlock(block);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、地块 " + block.getBlockNumber() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
//                    BeanValidators.validateWithException(validator, block);
//                    checkUserAllowed(block);
//                    checkUserDataScope(block.getUserId());
//                    block.setUpdateBy(operName);
                    block.setLastEditor(operName);
                    this.updateBlock(block);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、地块 " + block.getBlockNumber() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、地块 " + block.getBlockNumber() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、地块 " + block.getBlockNumber() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
